#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import configparser
import string, os, sys
import xml.dom.minidom
import ClassPathFileReader
import PropertiesReader

class GenerateConfigObj(object):
	def __init__(self,proname,needChannel,jarlist,dirname,projectpath):
		self.__proname = proname
		self.__needChannel = needChannel
		self.__jarlist = jarlist
		self.__dirname = dirname
		self.__projectpath = projectpath
	def getProName(self):
		return self.__proname
	def getNeedChannel(self):
		return self.__needChannel
	def getJarList(self):
		return self.__jarlist
	def getDirName(self):
		return self.__dirname
	def getProjectPath(self):
		return self.__projectpath

#configdict
project_config_list = []


#打印配置信息
def displayLibDict():
	for configobj in project_config_list:
		print("----------------------------------------")
		print("projectname:",configobj.getProName())
		print("dirname:",configobj.getDirName())
		print("needChannel:",configobj.getNeedChannel())
		print("projectpath:",configobj.getProjectPath())
		print("jarlist:",configobj.getJarList())

#XML添加子节点
def addPoint(dompt,fatherpt,ptname,attrdict):
	thispt = dompt.createElement(ptname)
	
	if(attrdict != None):
		for attname in attrdict:
			attvalue = attrdict[attname]
			thispt.setAttribute(attname,attvalue)
	
	fatherpt.appendChild(thispt)
	
	return thispt

#def 生成添加第三方classpath逻辑的<target
def addThirdLibPathTarget(paramDom,paramRoot,paramJarDirName,paramJarList):
	target = addPoint(paramDom,paramRoot,"target",{
		"name":"-pre-compile",
	})
	addPoint(paramDom,target,"echo",{
		"message":"JARPATH=${toString:tested.project.classpath}",
	})
	addPoint(paramDom,target,"property",{
		"name":"thirdlib.dir",
		"value":paramJarDirName,		
	})
	thirdlibpath = addPoint(paramDom,target,"path",{
		"id":"thirdlib.lib",
	})
	addPoint(paramDom,thirdlibpath,"path",{
		"path":"${toString:tested.project.classpath}",
	})	
	for jarname in paramJarList:
		addPoint(paramDom,thirdlibpath,"pathelement",{
			"location":"${thirdlib.dir}/" + jarname ,
		})	
	javapath = addPoint(paramDom,target,"path",{
		"id":"tested.project.classpath",
	})	
	addPoint(paramDom,javapath,"path",{
		"refid":"thirdlib.lib",
	})	
	addPoint(paramDom,target,"echo",{
		"message":"JARPATH=${toString:tested.project.classpath}",
	})

#def 生成多渠道打包逻辑的<target
def addMultiChannelPackTarget(paramDom,paramRoot):
	#<taskdef
#	taskdef = addPoint(paramDom,paramRoot,"taskdef",{
#		"resource":"net/sf/antcontrib/antcontrib.properties",
#	})
#	taskdefclasspath = addPoint(paramDom,taskdef,"classpath",None)
#	addPoint(paramDom,taskdefclasspath,"pathelement",{
#		"location":"${ant_contrib.dir}",
#	})

	#<target name="deploy" >
#	deployTarget = addPoint(paramDom,paramRoot,"target",{
#		"name":"deploy",
#	})
#	addPoint(paramDom,deployTarget,"foreach",{
#		"delimiter":",",
#		"list":"${market_channels}",
#		"param":"channel",
#		"target":"modify_manifest",
#	})

	#<target name="modify_manifest" >
	modifyManifestTarget = addPoint(paramDom,paramRoot,"target",{
		"name":"deploy",
	})
#	replaceregexpTarget = addPoint(paramDom,modifyManifestTarget,"replaceregexp",{
#		"encoding":"UTF-8",
#		"flags":"g",
#		"byline":"false",
#	})
#	addPoint(paramDom,replaceregexpTarget,"regexp",{
#		"pattern":r'meta-data[^/>]*android:name="${umeng_channel}"[^/>]*',
#	})
#	addPoint(paramDom,replaceregexpTarget,"substitution",{
#		"expression":r'meta-data android:name="${umeng_channel}" android:value="${market_channels}"',
#	})
#	addPoint(paramDom,replaceregexpTarget,"fileset",{
#		"dir":"",
#		"includes":"AndroidManifest.xml",
#	})
	addPoint(paramDom,modifyManifestTarget,"antcall",{
		"target":"clean",
	})
	addPoint(paramDom,modifyManifestTarget,"antcall",{
		"target":"release",
	})
	copyTarget = addPoint(paramDom,modifyManifestTarget,"copy",{
#		"tofile":"./output/${output.apk.name}_${market_channels}.apk",
		"tofile":"./output/${output.apk.name}.apk",		
	})
	addPoint(paramDom,copyTarget,"fileset",{
		"dir":"${out.absolute.dir}/",
		"includes":"${ant.project.name}-release.apk",
	})
	deleteTarget = addPoint(paramDom,modifyManifestTarget,"delete",{
		"includeEmptyDirs":"true",
	})
	addPoint(paramDom,deleteTarget,"fileset",{
		"dir":"${out.absolute.dir}",
		"includes":"**/*",
	})

#生成一个需要的custom_rules.xml文件
def generateOneCustomRulesXML(despath,bNeedMultiChannel,appname,jardirname,jarlist):
	impl = xml.dom.minidom.getDOMImplementation()
	dom = impl.createDocument(None,"project",None)
	root = dom.documentElement
	root.setAttribute("name","custom_rules")
	root.setAttribute("default","release")

	if("true" == bNeedMultiChannel):
		addMultiChannelPackTarget(dom,root)
	if(len(jardirname) > 0):
		addThirdLibPathTarget(dom,root,jardirname,jarlist)
	
	#write
	f= open(despath + appname + "_custom_rules.xml", "w", encoding="UTF-8")
	dom.writexml(f, addindent="  ", newl="\n",encoding="UTF-8")
	f.close()  

#根据project_config_list,生成所有的custom_rules.xml文件
def GenerateAllCustomRulesXML():
	for configobj in project_config_list:
		strCustomRulesFileDir = "./custom_rules/"
		if(False == os.path.exists(strCustomRulesFileDir)):
			os.makedirs(strCustomRulesFileDir)

		appname = configobj.getProName()
		bneedmulti = configobj.getNeedChannel()
		dirname = configobj.getDirName()
		jarlist = configobj.getJarList()
		generateOneCustomRulesXML(strCustomRulesFileDir,bneedmulti,appname,dirname,jarlist)	

#从配置文件中读取第三方jar包的目录名和文件名,存储到project_config_list中(已弃用)
#def readConfigFile():
#	userconfigfilepath = "./userconfig/genxml.conf"
#	if(False == os.path.exists(userconfigfilepath)):
#		raise Exception(userconfigfilepath + " 文件不存在,任务中断!")
#	
#	cf = configparser.ConfigParser()
#	cf.read(userconfigfilepath)
#
#	secs = cf.sections()
#	for sec in secs:
#		proname = sec
#		bNeedMulChannel = cf.get(sec,"isMainProject")
#		dirname = cf.get(sec,"dirname")
#		projectpath = cf.get(sec,"projpath")
#
#		jarnamelist = []
#		jarlist = cf.get(sec,"jarlist")
#		jarsplist = ';'
#		jarcount = jarlist.count(jarsplist)		
#		for jarname in jarlist.split(jarsplist,jarcount):
#			jarnamelist.append(jarname)
#
#		configobj = GenerateConfigObj(proname,bNeedMulChannel,jarnamelist,dirname,projectpath)
#		project_config_list.append(configobj)	

##读取gen.xml，根据配置，生成所有需要的custom_rules.xml
#def generateMulCustomRulesXMLByUserConfig():
#	readConfigFile()
#	GenerateAllCustomRulesXML()

#将一个工程的第三方jar包信息加入project_config_list
def readOneProJarInfo(classpathreader,projectpath,isMainPro):
	projectpath = projectpath.replace("\\","/")
	projectname = classpathreader.getProjectName(projectpath,".project")
	
	jarlist = classpathreader.getOneProThirdJarList(projectpath,".classpath")

	dirname = ""
	jarnamelist = []
	for jar in jarlist:
		dirname = jar.split('/',1)[0]
		jarnamelist.append(jar.split('/',1)[1])
	configobj = GenerateConfigObj(projectname,isMainPro,jarnamelist,dirname,projectpath)

	project_config_list.append(configobj)

#读取游戏以及依赖库的.classpath信息到project_config_list中
def readConfigFromClassPathFile(projectpath,propertiesfile):
	classpathreader = ClassPathFileReader.ClassPathFileReader()
	refprolist = PropertiesReader.getDupRemoveLibProject(projectpath,propertiesfile)

	readOneProJarInfo(classpathreader,projectpath,"true")

	for refpro in refprolist:
		readOneProJarInfo(classpathreader,refpro,"false")
		
#读取游戏以及依赖库的.classpath文件，生成custom_rules.xml
def generateMulCustomRulesXMLByProjectClasspath(projectpath,propertiesfile):
	readConfigFromClassPathFile(projectpath,propertiesfile)
	GenerateAllCustomRulesXML()
	
#main
if __name__=="__main__":
#	generateMulCustomRulesXMLByUserConfig()
	generateMulCustomRulesXMLByProjectClasspath("E:/gamecopy","project.properties")
	displayLibDict()


